// ComPort.cpp: implementation of the CComPort class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "8085.h"
#include "ComPort.h"
#include "MyException.h"
#include "globalfunctions.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CComPort::CComPort()
{
    m_hPort= NULL;
}

CComPort::~CComPort()
{
	Close( );
}

void CComPort::Open(tPort port)
{
    if(m_hPort)
        Close(); // close the previous handle
    CString szPort;
    szPort.Format("COM%d",port==COM1?0:1);
    Open(szPort);
}

void CComPort::Open(CString szPort)
{
    m_szPort = szPort;
    m_hPort = CreateFile(m_szPort,GENERIC_READ | GENERIC_WRITE,
        0,NULL,OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, // overlapped I/O
        NULL );

    if(INVALID_HANDLE_VALUE==m_hPort)
    {
        // could not open port
        CString szError = "Error opening "+m_szPort;
        throw CMyException(severe,comport_open,szError);
    }
}

void CComPort::Close()
{
	if ( m_hPort ) {
		CloseHandle(m_hPort);
		m_hPort = NULL;
	}
}

char CComPort::Read()
{
    char	temp[32];
    DWORD	bytesRead;
	BOOL	success;

    success = ReadFile(m_hPort,temp,1,&bytesRead,NULL);
	if ( !success ) {
		throw CMyException( severe, comport_read, GetWindowsErrorMessage( ) );
	}
    return temp[0];
}

void CComPort::Write(char c)
{
    DWORD bytesWritten;
	BOOL	success;
    success = WriteFile(m_hPort,(void *)c,1,&bytesWritten,NULL);
	if ( !success ) {
		throw CMyException( severe, comport_read, GetWindowsErrorMessage( ) );
	}
}